/*
 * hdfs.c
 *
 *  Created on: Feb 25, 2014
 *      Author: tiphan
 */
#include <msg/msg.h>
#include "hdfs.h"
#include "common.h"

XBT_LOG_NEW_DEFAULT_CATEGORY(msg_test);

void data_distributing(void)
{
	XBT_INFO(" ################################################################################# ");
	XBT_INFO(" Copying to HDFS ");

	int 	*rep = &(config.chunk_replicas);
	int 	*count = &(config.chunk_count);
	int 	*datanodes = &(config.number_of_datanodes);
	int 	chunk;
	chunk_mapping = xbt_new (char*, *count);

	if (*rep >= *datanodes) //each datanode has at least one replica of every chunks.
	{
		for (chunk = 0; chunk < *count; chunk++)
		{
			chunk_mapping[chunk] = xbt_new0 (char, *datanodes);
			int node = 0;
			for (node = 0; node < *datanodes; node++)
			{
				chunk_mapping[chunk][node] = node;
				//for each chunk, namenode proceduces a array of datanodes which store that chunk's replicas
			}
		}
	}
	else
	{
		for (chunk = 0; chunk < *count; chunk++)
		{
			chunk_mapping[chunk] = xbt_new0 (char, *rep);
		}
		hdfs(chunk_mapping, count, datanodes, rep);
	}
	XBT_INFO(" HDFS copying finished! ");
	XBT_INFO(" ################################################################################# ");
	return;
}

void hdfs(char** chunk_mapping, int *chunks, int *datanodes, int *replicas)
{
	int nodeID = 0;
	int i,j;
	for (i = 0; i < *chunks; i++)
	{
		for (j = 0; j < *replicas; j++)
		{
			chunk_mapping[i][j] = nodeID;
			XBT_INFO(" %d number %d -> %d ", i, j, chunk_mapping[i][j]);
			nodeID = ((nodeID + 1) < *datanodes) ? (nodeID + 1) : 0;
		}
	}

	return;
}

